package com.jiyun.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jiyun.mapper.DcCancelorderMapper;
import com.jiyun.pojo.DcCancelorder;
import com.jiyun.service.IDcCancelorderService;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.UUID;

/**
 * <p>
 * 取消订单表 服务实现类
 * </p>
 *
 * @author author
 * @since 2024-11-26
 */
@Service
public class DcCancelorderServiceImpl extends ServiceImpl<DcCancelorderMapper, DcCancelorder> implements IDcCancelorderService {
    @Value("${aliyun.endpoint}")
    String endPoint;
    @Value("${aliyun.keyid}")
    String accessKey;
    @Value("${aliyun.keysecret}")
    String secreKey;
    @Value("${aliyun.bucketname}")
    String bucketName;

    @Override
    public String savefile(MultipartFile file) {
        OSS ossClient = new OSSClientBuilder().build(endPoint, accessKey, secreKey);
        try {
            // 创建OSSClient实例。

            // 上传文件流。
            InputStream inputStream = file.getInputStream();
            String fileName = file.getOriginalFilename();
            //生成随机唯一值，使用uuid，添加到文件名称里面
            String uuid = UUID.randomUUID().toString().replaceAll("-","");
            fileName = uuid+fileName;
            //按照当前日期，创建文件夹，上传到创建文件夹里面
            //  2024/02/02/01.jpg
            String timeUrl = new DateTime().toString("yyyy/MM/dd");
            fileName = timeUrl+"/"+fileName;
            //调用方法实现上传
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, fileName, inputStream);
            PutObjectResult result = ossClient.putObject(putObjectRequest);
            // 关闭OSSClient。
            // https://spyx-spyx.oss-cn-beijing.aliyuncs.com/01.jpg
            String url = "https://"+bucketName+"."+endPoint+"/"+fileName;

            return url;
        }catch (OSSException oe) {
            System.out.println("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            System.out.println("Error Message:" + oe.getErrorMessage());
            System.out.println("Error Code:" + oe.getErrorCode());
            System.out.println("Request ID:" + oe.getRequestId());
            System.out.println("Host ID:" + oe.getHostId());
        }
        catch (Exception ce){
            System.out.println("Caught an ClientException, which means the client encountered ");
        } finally {
            if (ossClient != null){
                ossClient.shutdown();
            }
        }
        return null;
    }


}
